<template>
  <a-card class="general-card" title="行政地区" :bordered="false">
    <a-col :span="16" style="margin-bottom: 10px">
      <a-space>
        <a-button type="primary" @click="handleAsyncRegion">
          同步数据
        </a-button>
      </a-space>
    </a-col>
    <div class="flex">
      <a-tree :data="defaultData" :load-more="loadMores" style="width: 400px" h-600px overflow-y-auto @select="changeTree"
        :default-expand-selected="true" :default-expand-checked="true" />
      <a-form ref="formRef" :model="formValidate.form">
        <a-form-item v-if="formValidate.form.adCode" field="adCode" label="区域编码" :validate-trigger="['change']">
          <a-input v-model="formValidate.form.adCode" />
        </a-form-item>
        <a-form-item field="cityCode" label="城市代码" :validate-trigger="['change']">
          <a-input v-model="formValidate.form.cityCode" />
        </a-form-item>
        <a-form-item field="level" label="行政区划级别" :validate-trigger="['change']">
          <a-radio-group v-model="formValidate.form.level" type="button" disabled>
            <a-radio value="country">国家</a-radio>
            <a-radio value="province">省份</a-radio>
            <a-radio value="city">市</a-radio>
            <a-radio value="district">区县</a-radio>
            <a-radio value="street">街道</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="center" label="经纬度" :validate-trigger="['change']">
          <a-input v-model="formValidate.form.center" />
        </a-form-item>
        <a-form-item field="name" label="名称" :validate-trigger="['change']">
          <a-input v-model="formValidate.form.name" />
        </a-form-item>
        <a-form-item field="cityCode" label="排序" :validate-trigger="['change']">
          <a-input v-model="formValidate.form.orderNum" />
        </a-form-item>
        <a-form-item label="操作">

          <a-button style="margin-right: 10px" type="primary" :loading="formValidate.formLoading" html-type="submit"
            @click="handleInsert">添加</a-button>
          <a-button style="margin-right: 10px" :loading="formValidate.formLoading" html-type="submit"
            @click="handleUpdate">修改</a-button>
          <a-button type="primary" status="danger" :loading="formValidate.formLoading" html-type="submit"
            @click="handleDel">删除</a-button>
        </a-form-item>
      </a-form>
      <a-modal v-model:visible="modalFlag" title="添加" @ok="addSubmit">
        <a-form ref="formRef" :model="addValidate">
          <a-form-item label="父级">
            <a-input disabled v-model="addValidate.parentName" />
          </a-form-item>
          <a-form-item field="adCode" label="区域编码">
            <a-input v-model="addValidate.adCode" />
          </a-form-item>
          <a-form-item label="城市代码" field="cityCode">
            <a-input v-model="addValidate.cityCode" />
          </a-form-item>
          <a-form-item label="经纬度" field="center">
            <a-input v-model="addValidate.center" />
          </a-form-item>
          <a-form-item label="名称" field="name">
            <a-input v-model="addValidate.name" />
          </a-form-item>
          <a-form-item label="排序" field="orderNum">
            <a-input v-model="addValidate.orderNum" />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </a-card>
</template>

<script setup lang="ts">
import {
  getChildRegion,
  updateRegion,
  addRegion,
  delRegion,
} from '@/api/setting';
import { ref, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import useCurrentInstance from '@/hooks/useCurrentInstance';

const defaultData = ref<any>([]);
const modalFlag = ref(false) // 新增弹窗
// 获取modal
const modal = useCurrentInstance().globalProperties?.$modal;
// 数据集
const formValidate = ref<any>({
  enableAddModal: false,
  formLoading: false,
  fid: '', // 当前form的ids
  form: {
    adCode: '',
    cityCode: '',
    center: '',
    name: '',
    orderNum: '',
    level: '',
    enable: false,
  }, // 表单提交数据
});

const addValidate = ref<any>({
  parentName: "",
  adCode: "",
  cityCode: "",
  name: "",
  orderNum: "",
  center: "",
  level: ""
}); // 添加行政地区表单
// 树结构点击事件
const changeTree = (selectedKeys: any, data: any) => {
  if (data.node.cityCode == 'null') {
    data.node.cityCode = '';
  }
  formValidate.value.form = data.node;
};
const init = async () => {
  const id = 0;
  const res = await getChildRegion(id);
  if (res.data.success) {
    res.data.result.forEach((item: any) => {
      let data: any;
      if (item.name == '台湾省') {
        data = {
          ...item,
          title: item.name,
          key: item.id,
          isLeaf: true
        };
      } else {
        data = {
          ...item,
          title: item.name,
          loading: false,
          children: [],
          key: item.id
        };
      }
      defaultData.value.push(data);
      // spinning.value = false;
    });
  }
};

const loadMores: any = (nodeData: any) => {
  getChildRegion(nodeData.id).then((res) => {
    if (res.data.result.length <= 0) {
      return
    } else {
      res.data.result.forEach((child: any) => {
        console.log("child.level", child.level)
        let data;
        if (
          nodeData.label == 'district' || child.level == 'street' ||
          nodeData.label == '香港特别行政区' ||
          nodeData.label == '澳门特别行政区'
        ) {
          data = {
            ...child,
            title: child.name,
            key: child.id,
            isLeaf: true
          };
          delete child.children
          console.log(data, 'tips')
        }
        else {
          data = {
            ...child,
            title: child.name,
            loading: false,
            // isLeaf: true,
            children: [],
            key: child.id
          };
        }

        // spinning.value = false;
        nodeData.children.push(data);
        // resolve();
      });
    }
  });
};
// 同步数据
const handleAsyncRegion = () => {
  modal.confirm({
    title: '确定更新？',
    content: `更新后店铺以及用户地区绑定数据将全部错乱`,
    alignCenter: false,
    onOk: async () => {
      // const res = await asyncRegion();
      // Message.success('地区数据正在更新中！');
    },
  });
}
// 修改
const handleUpdate = () => {
  delete formValidate.value.form.createBy;
  delete formValidate.value.form.createTime;
  delete formValidate.value.form.updateBy;
  delete formValidate.value.form.updateTime;
  // delete formValidate.value.form.selected;
  updateRegion(formValidate.value.form.id, formValidate.value.form).then(
    (res) => {
      if (res.data.result) {
        Message.success('修改成功!,请稍后查看数据');
      }
    }
  );
};
// 删除
const handleDel = () => {
  modal.confirm({
    title: '确认删除',
    content: `删除后店铺以及用户地区绑定数据将全部错乱?`,
    alignCenter: false,
    onOk: async () => {
      const res = await delRegion(formValidate.value.form.id);
      if (res.data.success) {
        Message.success('删除成功!,请稍后查看数据');
        init()
      }
    },
  });
};



// 添加
const handleInsert = () => {
  if (!formValidate.value.form.parentId) {
    Message.error('请选择要添加的数据');
    return;
  }
  addValidate.value = JSON.parse(JSON.stringify(formValidate.value.form))
  const level = ["country", "province", "city", "district", "street"]
  let child = ""
  level.forEach((item, index) => {
    if (addValidate.value.level == item) {
      if (index == level.length - 1) {
        child = level[index - 1];
      } else {
        child = level[index + 1];
      }
    }
  })
  addValidate.value.level = child
  addValidate.value.parentId = formValidate.value.form.id;
  addValidate.value.parentName = formValidate.value.form.name;
  delete addValidate.value.id;
  delete addValidate.value.createBy;
  delete addValidate.value.createTime;
  delete addValidate.value.updateBy;
  delete addValidate.value.updateTime;
  delete addValidate.value.selected;
  addValidate.value.name = ""
  addValidate.value.center = ""
  modalFlag.value = true
};
// 提交数据
const addSubmit = () => {
  delete addValidate.value.children;
  console.log(addValidate.value, 'addValidate.value')
  addRegion(addValidate.value).then((res) => {
    if (res.data.success) {
      Message.success("添加成功!请稍后查看");
    }
  })
}
// 加载方法
onMounted(() => {
  init();
});
</script>
<style scoped lang="less">

</style>
